<?php
namespace app\common\model;
use x\Xbase;
class OrderGoods extends Xbase
{

    //获取子地区名称
    private function getAllAddress(){
        $rs = $this->db->query('select id,name from com_address');
        $map = [];
        foreach ($rs as $key => $value) {
            $map[$value['id']] = $value['name'];
        }
        return $map;
    }

    public function listsinfo($map=[],$o=0,$page=1,$limit=10){
        $w = where($map);
        $order = "";
        switch($o){
          case 1: //综合排序
            $order = "";
            break;
            default:
            $order = "order by a.order_no,a.id desc";
        }
        $sql = "select a.*,concat_ws('',title,'(',goods_price_title,')','X',nums) as goods_title
                  from order_goods as a
                  left join user b on a.user_id=b.id $w[0] {$order} ".limit($page,$limit);
        $rs = $this->db->query($sql,$w[1],'',true);
        return $rs;
    }

    public function groupLists($map=[],$o=0,$page=1,$limit=10){
        $w = where($map);
        $order = "";
        switch($o){
          case 1: //综合排序
            $order = "";
            break;
            default:
            $order = "order by a.id desc";
        }
        $sql = "select a.*,group_concat(concat_ws('',title,'(',goods_price_title,')','X',nums) separator '<br/>') as goods_title,sum(total_money) as sum_price
                  from order_goods as a
                  left join user b on a.user_id=b.id $w[0] group by a.order_no {$order} ".limit($page,$limit);
        $rs = $this->db->query($sql,$w[1],'',true);
        return $rs;
    }

    //订单详情
    public function orderInfo($map=[]){
        $w = where($map);
        $sql = "select o.*,u.username from order_goods as o inner join user as u on u.id = o.user_id $w[0]";
        $rs = $this->db->query($sql,$w[1]);
        return $rs;
    }

    #更新发货订单
    public function upfahuo($order_no){
        $order_goods = $this->db->query("select * from order_goods where order_no=? and refund_status!=?",[$order_no,2]);
        if (!$order_goods) return true;

        $check = true;
        foreach ($order_goods as $v) { if ($v['fahuo_status']==0) { $check=false;break; } }
        if ($check) $this->db->query("update order_goods_no set status=?,fh_time=? where order_no=?",[3,time(),$order_no]);
        return true;
    }


    /**
     * 下载订单
     * [downOrder description]
     * @param  [type] $nos [description]
     * @param  [type] $eid [description]
     * @return [type]      [description]
     */
    public function downOrder($order_no,$eid){
        $order_no = explode(',',$order_no);
        //查询订单
        $map = [
            ['and','order_no','in',$order_no]
        ];
        $w = where($map);
        $rs = $this->db->query("
        select
            a.*,b.username
        from order_goods as a
            inner join user as b on a.user_id = b.id
        $w[0] order by a.id desc",$w[1]);
        // //查询快递
        // $info = $this->db->query('select * from express where id = ?',[$eid],1);
        // foreach ($rs as $k => $v) {
        //     $rs[$k]["kd_name"] = $info['name'];
        // }
        $list = $this->db->query('select * from deploy');
        $temp = [];
        foreach ($list as $k => $v) {
            $temp[$v['name']] = $v['value'];
        }
        foreach ($rs as $k => $v) {
            $rs[$k]['goods_price_title'] = $v['title'] . ' ' . $v['goods_price_title'];
            $rs[$k]['fahuo_name'] = $temp['fahuo_name'];
            $rs[$k]['fahuo_phone'] = $temp['fahuo_phone'];
            $rs[$k]['fahuo_dizhi'] = $temp['fahuo_dizhi'];
            $rs[$k]['fahuo_youbian'] = $temp['fahuo_youbian'];
            $rs[$k]['daishouhuokuan'] = '';
            $rs[$k]['shoujianrenyuobian'] = '';
            $rs[$k]['shoujianrenguhua'] = '';
            $rs[$k]['baojiajine'] = '';
            $rs[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
        }
        switch ($eid) {
            case '1':
                $title = ['订单编号','物流公司编码','物流单号','会员名称','用户id','商品名称','数量','单价','总价','使用积分','获得积分','收件人姓名','收件人地址','收件人手机号','发件人姓名','发件人电话','发件人地址','发件人邮编','代收货款','备注','收件人邮编','收件人固话','保价金额','日期'];
                $fields= ['id','kd_code','kd_no','username','user_id','goods_price_title','nums','goods_price_price','total_money','use_points','points','sh_name','sh_address','sh_phone','fahuo_name','fahuo_phone','fahuo_dizhi','fahuo_youbian','daishouhuokuan','kd_note','shoujianrenyuobian','shoujianrenguhua','baojiajine','create_time'];
                break;
            default:
                $title = ['订单编号','物流公司编码','物流单号','会员名称','用户id','商品名称','数量','单价','总价','使用积分','获得积分','收件人姓名','收件人地址','收件人手机号','发件人姓名','发件人电话','发件人地址','发件人邮编','代收货款','备注','收件人邮编','收件人固话','保价金额','日期'];
                $fields= ['id','kd_code','kd_no','username','user_id','goods_price_title','nums','goods_price_price','total_money','use_points','points','sh_name','sh_address','sh_phone','fahuo_name','fahuo_phone','fahuo_dizhi','fahuo_youbian','daishouhuokuan','kd_note','shoujianrenyuobian','shoujianrenguhua','baojiajine','create_time'];
                break;
        }
        $file = com_csv($rs,$title,$fields,'order');
        return $file;
    }

    //申请退款
    public function apply_refund($id){
        $rs = $this->db->find('order_goods',$id);
        if(!$rs){
            return $this->setError('订单不存在!');
        }
        if( $rs['refund_status'] != 0 || $rs['sh_status'] != 0){
            return $this->setError('该订单不能申请退款!');
        }
        $order_goods_no = $this->db->query("select id,status from order_goods_no where order_no=?",[$rs['order_no']],1);
        if ($order_goods_no['status']>3) {
            return $this->setError('该订单状态错误!');
        }
        $this->db->update("order_goods_no",['refund_time' =>time()],['id=?',[$order_goods_no['id']]]);

        return $this->db->update("order_goods",['refund_status' =>1],['id=?',[$id]]);
    }

    //退款操作
    public function edit_refund($id,$type,$action_user_id){
        $info = $this->db->find('order_goods',$id);
        if(!$info){
            return $this->setError('订单不存在!');
        }
        if($info['refund_status'] != 1 && $info['sh_status'] != 0){
            return $this->setError('该订单不能执行该操作!');
        }
        $rs = 0;
        switch ($type) {
            case 0:
                $rs = $this->db->update('order_goods',['refund_status'=>0],['id=?',[$id]]);
                $msg = "取消退款申请，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            case 1:
                $order_no = com_order_no();
                $this->db->begin();
                $mysql = [];
                $mysql[] = $this->db->update('order_goods',['refund_status'=>2],['id=?',[$id]]);
                if ($info['total_money']-$info['use_points']>0) {
                    $mysql[] = m('Userbill','xcom')->doit($info['order_no'],$info["user_id"],111,'order_goods',$info['id'],$info['total_money']-$info['use_points'],'money','订单退款');
                }
                //退还积分
                if ($info['use_points']>0) {
                    $mysql[] = $order_id = m('Orderjifen','c')->add($order_no,$info["user_id"],$info['use_points'],5);
                    $mysql[] =m('Userbill','xcom')->doit($order_no,$info["user_id"],112,'order_jifen',$order_id,$info['use_points'],'money_jf','订单退款');
                }
                $rs = $this->db->end($mysql);
                if (!$rs) {
                    $this->setError('订单退款失败!');
                    return false;
                }
                $msg = "取消订单，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            case 2:
                $order_no = com_order_no();
                $this->db->begin();
                $mysql = [];
                $mysql[] = $this->db->update('order_goods',['refund_status'=>2],['id=?',[$id]]);
                if ($info['total_money']-$info['use_points']>0) {
                    $mysql[] = m('Userbill','xcom')->doit($info['order_no'],$info["user_id"],111,'order_goods',$info['id'],$info['total_money']-$info['use_points'],'money','订单退款');
                }
                //退还积分
                if ($info['use_points']>0) {
                    $mysql[] = $order_id = m('Orderjifen','c')->add($order_no,$info["user_id"],$info['use_points'],5);
                    $mysql[] =m('Userbill','xcom')->doit($order_no,$info["user_id"],112,'order_jifen',$order_id,$info['use_points'],'money_jf','订单退款');
                }
                $rs = $this->db->end($mysql);
                if (!$rs) {
                    $this->setError('订单退款失败!');
                    return false;
                }
                $msg = "同意退款申请，订单id【".$info['id']."】，编号【".$info['order_no']."】";
                m('Log','xcom')->record($action_user_id, $msg,'admin_user');
                break;
            default:

                break;
        }
        return $rs;
    }

}
